var host = "https://kk-exchanges.com";
var quote_list_4 = []
//四舍五入保留2位小数（不够位数，则用0替补）
function keepTwoDecimalFull(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
    }
    result = Math.round(num * 100) / 100;
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}
function showloading() {
    document.querySelector('.mask').style.display = 'block';
    document.querySelector('.loading').style.display = 'block';
    setTimeout(() => {
        document.querySelector('.mask').style.display = 'none';
        document.querySelector('.loading').style.display = 'none';
    }, 2000);
}
function hideloading() {
    setTimeout(() => {
        document.querySelector('.mask').style.display = 'none';
        document.querySelector('.loading').style.display = 'none';
    }, 2000);
}
function ajax(opt) {
    showloading();
    opt = opt || {};
    opt.method = opt.method.toUpperCase() || 'POST';
    opt.url = opt.url || ''; //请求地址
    opt.async = opt.async || false; //是否异步请求
    opt.data = opt.data || null; //传输数据
    opt.success = opt.success || function () { }; //服务器响应成功进行相应的处理
    var xmlHttp = null;
    if (XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest(); //服务器请求对象
    } else {
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); //兼容微软请求对象
    }
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            //响应是否成功
            var data = JSON.parse(xmlHttp.responseText);
            opt.success(data);
        }
        // hideloading();
    };
    var params = [];
    for (var key in opt.data) {
        // params.push(key + '=' + opt.data[key]);
        params.push(encodeURIComponent(key) + '=' + encodeURIComponent(opt.data[key]));
    }
    var postData = params.join('&');
    if (opt.method.toUpperCase() === 'POST') {
        //请求方法为POST,则执行如下操作
        xmlHttp.open(opt.method, opt.url, opt.async);
        xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        // xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        xmlHttp.setRequestHeader('app_language', 'Simplified_Chinese');
        xmlHttp.send(JSON.stringify(opt.data));
    } else if (opt.method.toUpperCase() === 'GET') {
        if (postData) {
            opt.url += '?' + postData
        }
        //请求方法为GET,则执行如下操作
        xmlHttp.open(opt.method, opt.url, opt.async);
        xmlHttp.setRequestHeader('app_language', 'Simplified_Chinese');
        xmlHttp.send(null);
    }
}
function get_config() {
    let opt = {};
    opt.url = host + "/api/app/config";
    opt.method = "GET";
    opt.success = function (res) {
        console.log('config: ', res);
        document.querySelector('#android_down a').href = res.data.androidAppUrl;
        document.querySelector('#ios_down a').href = res.data.iosAppUrl;
    }
    ajax(opt);
}
function get_news() {
    let opt = {};
    opt.url = host + "/api/app/basis/news";
    opt.method = "GET";
    opt.success = function (res) {
        console.log('news: ', res);
        render_news_items(res.data);
    }
    ajax(opt);
}
function get_helps() {
    let opt = {};
    opt.url = host + "/api/app/basis/help";
    opt.method = "GET";
    opt.success = function (res) {
        console.log('helps: ', res);
        render_news_items(res.data);
    }
    ajax(opt);
}
function change_article(e, id) {
    if (window.matchMedia("(max-width: 858px)").matches) {
        /* 窗口小于或等于 700 像素 */
        document.querySelector('.news-list').style.display = 'none';
        document.querySelector('.news-info').style.display = 'unset';
    } else {
        document.querySelector('.news-active').classList.remove('news-active');
        e.classList.add('news-active');
    }
    console.log('e.classList: ', e.classList);
    get_article_detail(id);
}
function get_article_detail(id) {  // id string
    let opt = {};
    opt.url = host + "/api/app/basis/article/detail";
    opt.method = "POST";
    params = {
        "id": id
    };
    opt.data = params
    opt.success = function (res) {
        console.log('article detail: ', res);
        let html_code = `
        <div class="news-t">${res.data.title}</div>
        <div class="news-time">${res.data.createTime}</div>
        <div class="news-detail">
            ${res.data.text}
        </div>
        `
        document.querySelector('.news-info').innerHTML = html_code;
    }
    ajax(opt);
}
function get_quotes_sort(req_type) {  // id string
    let opt = {};
    opt.url = host + "/api/app/quotes/sort";
    opt.method = "POST";
    params = {
        "type": req_type
    };
    opt.data = params
    opt.success = function (res) {
        console.log('get_quotes_sort: ', res);
        let html_code = `
        <div class="col-3">
            <div class="exchange-item">
                <div class="ei-row1">
                    <p class="coin">
                        <span class="coin-item">${res.data[0].coinName}/USDT</span>&nbsp;
                        <span class="range-lv ${res.data[0].range > 0 ? 'aquamarine' : 'f-red'}">${res.data[0].range > 0 ? '+' + keepTwoDecimalFull(res.data[0].range) : keepTwoDecimalFull(res.data[0].range)}%</span>
                    </p>
                </div>
                <div class="ei-row2">
                    <p class="coin-close ${res.data[0].range > 0 ? 'aquamarine' : 'f-red'}">${keepTwoDecimalFull(res.data[0].vol)}</p>
                </div>
                <div class="ei-row3">
                    <div class="chart1" style=""></div>
                    <!--<img src="static/img/${res.data[0].range > 0 ? 'chart-lv.png' : 'chart-red.png'}" alt="" srcset="">-->
                </div>
            </div>
        </div>
        <div class="col-3">
            <div class="exchange-item">
                <div class="ei-row1">
                    <p class="coin">
                        <span class="coin-item">${res.data[1].coinName}/USDT</span>&nbsp;
                        <span class="range-lv ${res.data[1].range > 0 ? 'aquamarine' : 'f-red'}">${res.data[1].range > 0 ? '+' + keepTwoDecimalFull(res.data[1].range) : keepTwoDecimalFull(res.data[1].range)}%</span>
                    </p>
                </div>
                <div class="ei-row2">
                    <p class="coin-close ${res.data[1].range > 0 ? 'aquamarine' : 'f-red'}">${keepTwoDecimalFull(res.data[1].vol)}</p>
                </div>
                <div class="ei-row3">
                <div class="chart2" style=""></div>
                <!--<img src="static/img/${res.data[1].range > 0 ? 'chart-lv.png' : 'chart-red.png'}" alt="" srcset="">-->
                </div>
            </div>
        </div>
        <div class="col-3">
            <div class="exchange-item">
                <div class="ei-row1">
                    <p class="coin">
                        <span class="coin-item">${res.data[2].coinName}/USDT</span>&nbsp;
                        <span class="range-lv ${res.data[2].range > 0 ? 'aquamarine' : 'f-red'}">${res.data[2].range > 0 ? '+' + keepTwoDecimalFull(res.data[2].range) : keepTwoDecimalFull(res.data[2].range)}%</span>
                    </p>
                </div>
                <div class="ei-row2">
                    <p class="coin-close ${res.data[2].range > 0 ? 'aquamarine' : 'f-red'}">${keepTwoDecimalFull(res.data[2].vol)}</p>
                </div>
                <div class="ei-row3">
                <div class="chart3" style=""></div>
                <!--<img src="static/img/${res.data[2].range > 0 ? 'chart-lv.png' : 'chart-red.png'}" alt="" srcset="">-->
                </div>
            </div>
        </div>
        <div class="col-3 last-coin" style="border-right: unset;">
            <div class="exchange-item">
                <div class="ei-row1">
                    <p class="coin">
                        <span class="coin-item">${res.data[3].coinName}/USDT</span>&nbsp;
                        <span class="range-lv ${res.data[3].range > 0 ? 'aquamarine' : 'f-red'}">${res.data[3].range > 0 ? '+' + keepTwoDecimalFull(res.data[3].range) : keepTwoDecimalFull(res.data[3].range)}%</span>
                    </p>
                </div>
                <div class="ei-row2">
                    <p class="coin-close ${res.data[3].range > 0 ? 'aquamarine' : 'f-red'}">${keepTwoDecimalFull(res.data[3].vol)}</p>
                </div>
                <div class="ei-row3">
                    <div class="chart4" style=""></div>
                    <!--<img src="static/img/${res.data[3].range > 0 ? 'chart-lv.png' : 'chart-red.png'}" alt="" srcset="">-->
                </div>
            </div>
        </div>
        `
        document.querySelector('.exchange-1').innerHTML = html_code;
        quote_list_4 = res.data.slice(0, 4)
        render_quotes();
        // 表格
        let t_html_code = ``
        res.data.forEach(function (v, i, arr) {
            let tmp_code = `<div class="t-tr">
            <div class="t-td last-coin">${i + 1}</div>
            <div class="t-td">${v.coinName}/USDT</div>
            <div class="t-td last-coin">9710.15亿</div>
            <div class="t-td">≈$ ${v.close}</div>
            <div class="t-td ${v.range > 0 ? 'aquamarine' : 'f-red'} text-r">${v.range > 0 ? '+' + v.range : v.range}%</div>
        </div>`
            t_html_code += tmp_code;
        });
        document.querySelector('.t-body').innerHTML = t_html_code;
    }
    ajax(opt);
}
function to_home() {
    document.querySelector('.body').style.display = 'unset';
    document.querySelector('.news').style.display = 'none';
}
function to_news() {
    document.querySelector('.news').style.display = 'block';
    document.querySelector('.body').style.display = 'none';
    document.querySelector('.news-title').innerHTML = '公告中心';
    if (window.matchMedia("(max-width: 858px)").matches) {
        /* 窗口小于或等于 700 像素 */
        document.querySelector('.news-list').style.display = 'unset';
        document.querySelector('.news-info').style.display = 'none';
    }
    get_news();
}
function to_helps() {
    document.querySelector('.news').style.display = 'block';
    document.querySelector('.body').style.display = 'none';
    document.querySelector('.news-title').innerHTML = '帮助中心';
    if (window.matchMedia("(max-width: 858px)").matches) {
        /* 窗口小于或等于 700 像素 */
        document.querySelector('.news-list').style.display = 'unset';
        document.querySelector('.news-info').style.display = 'none';
    }
    get_helps();
}
function render_news_items(list) {
    let html_code = ``;
    list.forEach(function (v, i, arr) {
        let html_code_tmp = ``
        if (i === 0) {
            get_article_detail(v.id);
            html_code_tmp = `
            <div class="news-item news-active" onclick="change_article(this, '${v.id}')">
                <div class="n-title">${v.title}</div>
                <div class="n-time">${v.createTime}</div>
            </div>
            `
        } else {
            html_code_tmp = `
            <div class="news-item" onclick="change_article(this, '${v.id}')">
                <div class="n-title">${v.title}</div>
                <div class="n-time">${v.createTime}</div>
            </div>
            `
        }
        html_code += html_code_tmp;
    });
    document.querySelector('.news-items').innerHTML = html_code;
}
function change_menu(e) {
    let lis = document.querySelectorAll('nav ul li a.active');
    lis.forEach(function (v, i, arr) {
        v.classList.remove('active');
    })
    e.classList = ['active'];
    if (e.text === '首页') {
        to_home();
    } else if (e.text === '公告') {
        to_news();
    } else if (e.text === '帮助') {
        to_helps();
    } else if (e.text === '介绍') {
        to_home();
    } else if (e.text === '下载') {
        to_home();
    }
}

function render_chart(quote, element) {
    let quote_list = [];
    let this_quotes = quote.quotes;
    let quotes_min = Math.min.apply(Math, this_quotes);
    for (let i = 0; i < this_quotes.length; i++) {
        const v = this_quotes[i];
        quote_list.push([i, parseFloat(v - quotes_min)]);
    }
    let color_l = 'rgba(127,255,212';
    let line_color = 'aquamarine';
    if (quote.range < 0) {
        line_color = 'red';
        color_l = 'rgba(255,0,0';
    }
    let option = {
        xAxis: {
            type: 'time',
            show: false,
        },
        yAxis: {
            type: 'value',
            show: false,
        },
        series: [
            {
                type: 'line',
                data: quote_list,
                symbol: "none",
                itemStyle: {
                    normal: {
                        color: line_color,
                        lineStyle: {
                            width: 1.5,
                            type: 'solid'  //'dotted'虚线 'solid'实线
                        }
                    }
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 0.5, [{
                        offset: 0,
                        color: color_l + ',0.8)'
                    },
                    {
                        offset: 1,
                        color: color_l + ',0)'
                    }])
                },
            }]
    };
    let myChart = echarts.init(element);

    // option.series[0].data = ch_data;
    myChart.setOption(option);
}
function render_quotes() {
    quote_list = quote_list_4 || [];
    for (let index = 0; index < quote_list.length; index++) {
        const quote = quote_list[index];
        let selected = '.chart' + (index + 1).toString();
        let element = document.querySelector(selected);
        if (element) {
            render_chart(quote, element);
        }
    }
}

function change_lang(ele) {
    // debugger;
    console.log('change_lang to:', ele.textContent);
    $("input[type='checkbox']").prop('checked', false);
}

// function blur_box(ele) {
//     setTimeout(() => {
//         $("input[type='checkbox']").focus();
//         $("input[type='checkbox']").prop('checked', false);
//     }, 1500)
// }
